/*
 * String manipulation
 *
 * Copyright 2022, 2023, and 2024 Odin Kroeger.
 *
 * This file is part of suCGI.
 *
 * suCGI is free software: you can redistribute it and/or modify it
 * under the terms of the GNU Affero General Public License as published
 * by the Free Software Foundation, either version 3 of the License,
 * or (at your option) any later version.
 *
 * suCGI is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General
 * Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public
 * License along with suCGI. If not, see <https://www.gnu.org/licenses/>.
 */

#define _XOPEN_SOURCE 700

#if defined(__OPTIMIZE__) && !defined(_FORTIFY_SOURCE)
#define _FORTIFY_SOURCE 3
#endif

#include <assert.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdlib.h>
#include <string.h>

#include "params.h"
#include "str.h"
#include "types.h"


Error
str_split(const char *const str, const char *const sep,
          const size_t size, char *const head, const char **const tail)
{
    assert(str != NULL);
    assert(size <= MAX_STR_LEN);
    assert(strnlen(str, MAX_STR_LEN) < MAX_STR_LEN);
    assert(sep != NULL);
    assert(strnlen(sep, MAX_STR_LEN) < MAX_STR_LEN);
    assert(size > 0U);
    assert(head != NULL);
    assert(tail != NULL);

    *tail = strpbrk(str, sep);
    if (*tail == NULL) {
        if (memccpy(head, str, '\0', size)) {
            return OK;
        }

        return ERR_LEN;
    }

    assert(*tail >= str);

    /* cppcheck-suppress misra-c2012-18.4; safe pointer subtraction */
    ptrdiff_t len = *tail - str;
    assert(len >= 0);
    assert((uintmax_t) len < (uintmax_t) SIZE_MAX);

    if ((size_t) len >= size) {
        return ERR_LEN;
    }

    char *const end = stpncpy(head, str, (size_t) len);
    *end = '\0';
    ++(*tail);

    return OK;
}
